package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.entity.User;
import com.itheima.serivce.UserService;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    //{phone:"123456"}
    @PostMapping("/sendMsg")
    public R<String> sendMsg(HttpServletRequest request, @RequestBody Map<String, String> map) {
        String phone = map.get("phone");
        String code = ValidateCodeUtils.generateValidateCode4String(4);
        //收到验证码
//        SMSUtils.sendMessage(phone, code);
        log.info("短信验证码：{}", code);
        //真实的存储在session中，key是手机号
        //Redis 原始储存的session
        //request.getSession().setAttribute(phone, code);
        String ph = ("code_" + phone);
        redisTemplate.opsForValue().set(ph,code,5, TimeUnit.MINUTES);
        return R.success("短信发送成功");
    }

    @PostMapping("/login")
    public R<String> login(HttpServletRequest request, @RequestBody Map<String, String> map) {
        String phone = map.get("phone");
        String code = map.get("code");
        //根据手机号 从session获取存入真实验证码
        //String realCode = (String) request.getSession().getAttribute(phone);

        String ph = ("code_" + phone);
        Object realCode = redisTemplate.opsForValue().get(ph);

        if (realCode == null) {
            return R.error("手机号不准确或者验证码过期");
        }
        //比较验证码
        if (!code.equals(realCode)) {
            return R.error("验证码填写错误");
        }
        /*
            登录成功：
            1.如果用户是第一次登录，就要把当前手机号自动注册到mysql中保存起来，以后时不时发送节日活动短信。
            2.不是第一次登录，就不存
         */

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(phone != null, User::getPhone, phone);
        User user = userService.getOne(wrapper);
        if (user == null) {
            //新用户
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        }
        if (user.getStatus() != 1) {
            //用户被禁用
            return R.error("用户被禁用");
        }
        request.getSession().setAttribute("user", user);

        redisTemplate.delete(ph);
        return R.success("登录成功");
    }
}
